﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SpriteBuilder
{
    public class ImageInfo
    {
        public string FileName;
        public string FilePath;
        public int Height;
        public int Width;
        public int RowNumber;
        public int ColumnNumber;
    }

    public partial class Form1 : Form
    {
        private Dictionary<string, string> FileList;

        private List<ImageInfo> _AddedFiles;
        private List<ImageInfo> AddedFiles
        {
            get
            {
                return _AddedFiles = _AddedFiles ?? new List<ImageInfo>();
            }
            set { _AddedFiles = value; }
        }

        private List<string> _DirectionList;
        private List<string> DirectionList
        {
            get
            {
                if (_DirectionList == null)
                {
                    _DirectionList = new List<string>
                    {
                        "North",
                        "NorthEast",
                        "East",
                        "SouthEast",
                        "South",
                        "SouthWest",
                        "West",
                        "NorthWest"
                    };
                }

                return _DirectionList;
            }
        }

        private List<string> _ActionList;
        private List<string> ActionList
        {
            get
            {
                if (_ActionList == null)
                {
                    _ActionList = new List<string>
                    {
                        "Attack",
                        "Charge",
                        "Deliver",
                        "Die",
                        "Face",
                        "Idle",
                        "Shoot",
                        "Walk"
                    };
                }

                return _ActionList;
            }
        }



        public Form1()
        {
            InitializeComponent();

            lbDirections.Visible = false;
            lblDirection.Visible = false;

            foreach (var action in ActionList)
            {
                lbActions.Items.Add(action);
            }

            btnSave.Enabled = false;
        }

        private void LoadData(bool clear)
        {
            if (clear)
            {
                cblImages.Items.Clear();
            }

            if (FileList != null)
            {
                foreach (var file in FileList)
                {
                    cblImages.Items.Add(file.Key);
                }
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            var fileDialog = new OpenFileDialog
            {
                InitialDirectory = @"C:\Users\jan-willem\Desktop\kam remake c\sprites\units\BattleUnits\",
                Filter = "Png files (*.png)|*.png|All files (*.*)|*.*",
                FilterIndex = 0,
                RestoreDirectory = true,
                Multiselect = true
            };

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                FileList = new Dictionary<string, string>();

                for (int i = 0; i < fileDialog.FileNames.Count(); i++)
                {
                    FileList.Add(fileDialog.SafeFileNames[i], fileDialog.FileNames[i]);
                }
            }

            btnSave.Enabled = true;

            LoadData(false);
        }

        private void cblImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cblImages.SelectedItem != null)
            {
                var filename = FileList[cblImages.SelectedItem.ToString()];

                if (File.Exists(filename))
                {
                    pbImage.Image = new Bitmap(filename);
                }
            }
        }

        private void lbDirections_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetFileNameTextBox();
        }

        private void lbActions_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetFileNameTextBox();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btAddToRow_Click(object sender, EventArgs e)
        {
            int rowNumber = -1;
            if (int.TryParse(tbRowNumber.Text, out rowNumber))
            {
                foreach (var fileName in cblImages.CheckedItems)
                {
                    using (var bitmap = Bitmap.FromFile(FileList[fileName.ToString()]))
                    {
                        AddedFiles.Add(new ImageInfo
                        {
                            FileName = fileName.ToString(),
                            FilePath = FileList[fileName.ToString()],
                            RowNumber = rowNumber,
                            ColumnNumber = AddedFiles.Count(x => x.RowNumber == rowNumber) + 1,
                            Width = bitmap.Width,
                            Height = bitmap.Height
                        });

                        FileList.Remove(fileName.ToString());
                    }
                }

                LoadData(true);
                SetAddedList();
            }
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            int totalWidth, totalHeight, columnWidth, rowHeight, colCount, rowCount;

            // calculate maximum column width size that is possible
            columnWidth = AddedFiles.Max(x => x.Width);

            // calculate the max column height
            rowHeight = AddedFiles.Max(x => x.Height);

            // get the amount of columns
            colCount = AddedFiles.GroupBy(x => x.RowNumber).Max(group => group.Count());

            // get the amount of rows 
            rowCount = AddedFiles.GroupBy(x => x.RowNumber).Count();

            // calculate the image rowheight;
            totalHeight = rowHeight * rowCount;

            // calculate the image rowheight;
            totalWidth = columnWidth * colCount;


            Bitmap newSprite = new Bitmap(totalWidth, totalHeight);

            using (Graphics g = Graphics.FromImage(newSprite))
            {
                foreach (var image in AddedFiles)
                {
                    using (Bitmap file = new Bitmap(image.FilePath))
                    {
                        //          calculate the normal width position   center the image 
                        int width = columnWidth * (image.ColumnNumber - 1) + ((columnWidth - image.Width));

                        //           calculate the normal heightposition   add the imagedifference so it will start bottom left
                        int height = (rowHeight * (image.RowNumber - 1)) + (rowHeight - image.Height) ;

                        g.DrawImage(file, width, height);

                        // draw a border around the 
                        g.DrawRectangle(new Pen(Brushes.Black, 1), new Rectangle(columnWidth * (image.ColumnNumber - 1), (rowHeight * (image.RowNumber - 1)), columnWidth, rowHeight));
                    }
                }
            }

            newSprite.Save(Path.Combine(Path.GetDirectoryName(AddedFiles.First().FilePath), tbFileName.Text));
        }



        private void btClear_Click(object sender, EventArgs e)
        {
            int rowNumber = -1;
            if (int.TryParse(tbRowNumber.Text, out rowNumber))
            {
                for (int i = 0; i < AddedFiles.Count(); i++)
                {
                    if (AddedFiles[i] != null && AddedFiles[i].RowNumber == rowNumber)
                    {
                        AddedFiles.Remove(AddedFiles[i]);
                    }
                }
            }
            else
            {
                AddedFiles.Clear();
            }

            SetAddedList();
        }


        private void SetAddedList()
        {
            var totalString = new StringBuilder();

            for (int i = 1; i <= AddedFiles.Max(x => x.RowNumber); i++)
            {
                if (AddedFiles.Any(x => x.RowNumber == i))
                {
                    totalString.AppendLine(string.Format("row {0}", i));

                    foreach (ImageInfo image in AddedFiles.Where(x => x.RowNumber == i))
                    {
                        totalString.AppendLine(image.FilePath);
                    }
                }
            }

            ttAdded.SetToolTip(lblAddedFiles, totalString.ToString());
        }

        private void SetFileNameTextBox()
        {
            string direction = "", action = "";

            if (lbActions.SelectedItem != null)
            {
                action = lbActions.SelectedItem.ToString();
            }

            //if (lbDirections.SelectedItem != null)
            //{
            //    direction = lbDirections.SelectedItem.ToString();
            //}

            //tbFileName.Text = string.Format("{0}_{1}.png", direction, action);

            tbFileName.Text = string.Format("{0}.png", action);
        }

        /// <summary>
        /// when the image is clicked save the clicked coordination
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbImage_Click(object sender, EventArgs e)
        {

        }


    }
}
